<?php

namespace api\libs\event\components;

use api\components\RequestClient;
use api\models\ChangeList;
use api\modules\app\models\MetaArea;
use api\modules\app\models\TaskRecord;
use mongosoft\soapclient\Client;
use Yii;
use api\libs\event\models\EventLog;
use yii\base\Component;
use api\libs\event\models\Event;
use api\components\Notification;
use yii\db\Exception;

/**
 * 事件监听类用于记录日志
 *
 * @author johnson
 * @date 2019-03-18
 * @access public
 */
class EventListener extends Component {

    /**
     * consultant save event log
     * @param array $event 例如
     * array(
     *  'name'=> 'campaign.create',
     *           'object' => EventLog::TYPE_CAMPAIGN,
     *           'objectid' => 14234,
     *           'data' => array(
     *                      'name' => '测试项目',
     *                      'clientname' => '测试客户',
     *            ))
     */
    public static function onSaveEventLogs($event) {
        $sender = $event->sender;
        $data = $event->data;
        if (isset($data['event_name']) && isset($sender['id']) && isset($data['object'])) {
            self::saveEventLogs($sender, $data);
        } else {
            Yii::error('Missing Parameters.');
        }
    }

    /**
     * 保存日志
     * @param mixed $data 日志描述
     * @param mixed $data 日志描述
     * @return bool TRUE-添加事件生成 FALSE-添加事件失败
     * @throws CHttpException
     */
    public static function saveEventLogs($sender, $data) {
        $management = Event::findOne(array('name' => trim($data['event_name'])));
        if (empty($management)) {
            Yii::error('Event Rule Is Not Found.');
        }
        if ($management->valid) {
            if (isset($data['type'])) {
                $log = EventLog::model()->findByAttributes(array('objectid' => $sender['id'], 'object' => $data['object'], 'eventid' => $management->id));
            } else {
                $log = new EventLog();
            }
            if (NULL == $log) {
                $log = new EventLog();
            }
            $log->eventid = $management->id;
            $log->type = $management->type;
            $log->objectid = $sender['id'];
            $log->object = $data['object'];
            $log->data = $sender['attributes'];
            $log->status = EventLog::STATUS_SUCCESS;
            $log->save();
            return TRUE;
        }
        return FALSE;
    }
    

    public static function onSaveNotification($event) {
        $sender = $event->sender;
        $data = $event->data;
        if (!empty($event->template_name) && !empty($event->type)) {
            Notification::send($event->uids, $event->type, $event->template_name, $event->params);
        } else {
            Yii::error('Missing Parameters.');
        }
    }

    public static function onSaveTaskRecord($event) {
        $model = new TaskRecord();
        try {
            if (!empty($event->recipient) && !empty($event->cuser) && !empty($event->task_id)) {
                if (!is_array($event->recipient)) {
                    $event->recipient = explode(',', $event->recipient);
                }
                foreach ($event->recipient as $recipient) {
                    $_model = clone $model;
                    $_model->task_id = $event->task_id;
                    $_model->recipient = $recipient;
                    $_model->cuser = $event->cuser;
                    $_model->save();
                }
            } else {
                Yii::error('Missing Parameters.');
            }
        } catch (Exception $e) {
            
        }
    }

    public static function onPush($event) {
        $source = $event->sender;
        $data = $event->data;
//        if (isset($data['table']) && isset($data['key']) && isset($data['opt']) && isset($source['id']) && isset($data['object'])) {
//            $client = new RequestClient(['source' => $source, 'data' => $data]);
//            $client->pushData();
            Yii::$app->queue->push(new RequestClient(['source' => $source, 'data' => $data]));
//        } else {
//            Yii::error('Missing Parameters.',__METHOD__);
//        }
    }

    public static function onPushExt($source,$data)
    {
//        if (isset($data['table']) && isset($data['key']) && isset($data['opt']) && isset($source['id']) && isset($data['object'])) {
//            $client = new RequestClient(['source' => $source, 'data' => $data]);
//            return $client->pushData();
            Yii::$app->queue->push(new RequestClient(['source' => $source, 'data' => $data]));
//        } else {
//            Yii::error('Missing Parameters.',__METHOD__);
//            return true;
//        }
    }

}
